package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    private static final String grantType = "authorization_code";
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录生产code
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("appid",weChatProperties.getAppid());
        hashMap.put("secret",weChatProperties.getSecret());
        hashMap.put("js_code",userLoginDTO.getCode());
        hashMap.put("grant_type",grantType);
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, hashMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openId = jsonObject.getString("openid");

        User user = userMapper.selectByOpenid(openId);
        //判断openId是否为空从而判断其是否为新用户 新用户要插入数据
        if(Objects.isNull(user)){
            user = User.builder()
                .openid(openId)
                .createTime(LocalDateTime.now())
                .build();
            userMapper.insert(user);
        }
        return user;
    }
}
